// 学习工具函数

// 计算单词学习进度
export const calculateLearningProgress = (wordStats) => {
  if (!wordStats || !wordStats.length) return 0
  
  const totalWords = wordStats.length
  const masteredWords = wordStats.filter(stat => stat.masteryLevel >= 4).length
  
  return Math.round((masteredWords / totalWords) * 100)
}

// 计算学习计划完成度
export const calculatePlanCompletion = (plan, progress) => {
  if (!plan || !progress) return 0
  
  const { dailyGoal } = plan
  const { wordsLearnedToday } = progress
  
  const completionRate = wordsLearnedToday / dailyGoal
  
  // 限制在100%以内
  return Math.min(Math.round(completionRate * 100), 100)
}

// 计算学习效率
export const calculateLearningEfficiency = (totalTimeSpent, wordsLearned) => {
  if (!totalTimeSpent || !wordsLearned) return 0
  
  // 分钟/单词
  const minutesPerWord = totalTimeSpent / 60 / wordsLearned
  
  // 效率评分（值越高越好）
  if (minutesPerWord < 0.5) return 100
  if (minutesPerWord < 1) return 90
  if (minutesPerWord < 2) return 80
  if (minutesPerWord < 3) return 70
  if (minutesPerWord < 5) return 60
  if (minutesPerWord < 10) return 40
  return 20
}

// 生成学习建议
export const generateLearningSuggestions = (wordStats, studyPlan) => {
  const suggestions = []
  
  // 检查学习频率
  const lastStudyTime = wordStats.reduce((latest, stat) => {
    return stat.lastReviewed > latest ? stat.lastReviewed : latest
  }, 0)
  
  const daysSinceLastStudy = (Date.now() - lastStudyTime) / (1000 * 60 * 60 * 24)
  
  if (daysSinceLastStudy > 3) {
    suggestions.push('您已经有一段时间没有学习了，建议恢复每日学习习惯。')
  }
  
  // 检查单词掌握情况
  const poorlyMasteredWords = wordStats.filter(stat => stat.masteryLevel < 2).length
  const totalWords = wordStats.length
  
  if (poorlyMasteredWords > totalWords * 0.3) {
    suggestions.push('有较多单词掌握不牢固，建议加强复习。')
  }
  
  // 检查学习计划完成情况
  if (studyPlan && studyPlan.dailyGoal) {
    const today = new Date().toDateString()
    const todayProgress = wordStats.filter(stat => 
      new Date(stat.lastReviewed).toDateString() === today
    ).length
    
    if (todayProgress < studyPlan.dailyGoal * 0.5) {
      suggestions.push(`今日学习进度不足，还需要学习 ${studyPlan.dailyGoal - todayProgress} 个单词。`)
    }
  }
  
  // 提供个性化建议
  if (suggestions.length === 0) {
    suggestions.push('您的学习状态良好，继续保持！')
  }
  
  return suggestions
}

// 根据艾宾浩斯遗忘曲线计算复习时间
export const calculateReviewSchedule = (wordStat) => {
  const { lastReviewed, masteryLevel } = wordStat
  const now = Date.now()
  
  // 如果从未复习过，立即复习
  if (!lastReviewed) {
    return now
  }
  
  // 根据掌握程度确定复习间隔（天数）
  let intervalDays = 1
  
  switch (masteryLevel) {
    case 1:
      intervalDays = 1 // 1天后
      break
    case 2:
      intervalDays = 3 // 3天后
      break
    case 3:
      intervalDays = 7 // 7天后
      break
    case 4:
      intervalDays = 15 // 15天后
      break
    case 5:
      intervalDays = 30 // 30天后
      break
    default:
      intervalDays = 1
  }
  
  // 计算下次复习时间
  const nextReviewTime = new Date(lastReviewed)
  nextReviewTime.setDate(nextReviewTime.getDate() + intervalDays)
  
  return nextReviewTime.getTime()
}

// 获取需要复习的单词
export const getWordsToReview = (wordStats) => {
  const now = Date.now()
  
  return wordStats
    .map(word => ({
      ...word,
      nextReviewTime: calculateReviewSchedule(word)
    }))
    .filter(word => word.nextReviewTime <= now)
    .sort((a, b) => a.nextReviewTime - b.nextReviewTime)
}

// 计算单词难度等级
export const calculateWordDifficulty = (wordStats) => {
  const { attempts, successes, masteryLevel } = wordStats
  
  // 如果尝试次数不足，默认中等难度
  if (attempts < 3) {
    return 3
  }
  
  // 计算成功率
  const successRate = successes / attempts
  
  // 根据成功率和掌握程度计算难度
  let difficulty = 3 // 中等难度
  
  if (successRate < 0.4 || masteryLevel <= 1) {
    difficulty = 5 // 非常困难
  } else if (successRate < 0.6 || masteryLevel <= 2) {
    difficulty = 4 // 困难
  } else if (successRate >= 0.8 && masteryLevel >= 4) {
    difficulty = 1 // 非常简单
  } else if (successRate >= 0.6 || masteryLevel >= 3) {
    difficulty = 2 // 简单
  }
  
  return difficulty
}

// 根据难度分级单词
export const groupWordsByDifficulty = (wordStats) => {
  const groups = {
    1: [], // 非常简单
    2: [], // 简单
    3: [], // 中等
    4: [], // 困难
    5: []  // 非常困难
  }
  
  wordStats.forEach(word => {
    const difficulty = calculateWordDifficulty(word)
    groups[difficulty].push(word)
  })
  
  return groups
}

// 生成学习序列
export const generateLearningSequence = (wordStats, options = {}) => {
  const { 
    includeNewWords = true, 
    includeReviewWords = true, 
    priority = 'mixed', // 'new', 'review', 'mixed', 'difficulty'
    count = 20 
  } = options
  
  const sequence = []
  const now = Date.now()
  
  // 分离新单词和复习单词
  const newWords = wordStats.filter(word => !word.lastReviewed)
  const reviewWords = getWordsToReview(wordStats)
  
  // 根据优先级生成序列
  switch (priority) {
    case 'new':
      // 优先新单词
      if (includeNewWords) {
        sequence.push(...newWords.slice(0, count))
      }
      if (sequence.length < count && includeReviewWords) {
        sequence.push(...reviewWords.slice(0, count - sequence.length))
      }
      break
      
    case 'review':
      // 优先复习单词
      if (includeReviewWords) {
        sequence.push(...reviewWords.slice(0, count))
      }
      if (sequence.length < count && includeNewWords) {
        sequence.push(...newWords.slice(0, count - sequence.length))
      }
      break
      
    case 'difficulty':
      // 按难度排序
      const allWords = [...(includeReviewWords ? reviewWords : []), ...(includeNewWords ? newWords : [])]
      allWords.sort((a, b) => {
        const difficultyA = calculateWordDifficulty(a)
        const difficultyB = calculateWordDifficulty(b)
        return difficultyB - difficultyA
      })
      sequence.push(...allWords.slice(0, count))
      break
      
    case 'mixed':
    default:
      // 混合模式
      const mixedSequence = []
      let newIndex = 0
      let reviewIndex = 0
      
      // 混合策略：先复习，再学习新单词，比例3:1
      while (mixedSequence.length < count) {
        if (includeReviewWords && reviewIndex < reviewWords.length && mixedSequence.length % 4 !== 0) {
          mixedSequence.push(reviewWords[reviewIndex])
          reviewIndex++
        } else if (includeNewWords && newIndex < newWords.length) {
          mixedSequence.push(newWords[newIndex])
          newIndex++
        } else if (includeReviewWords && reviewIndex < reviewWords.length) {
          mixedSequence.push(reviewWords[reviewIndex])
          reviewIndex++
        } else if (includeNewWords && newIndex < newWords.length) {
          mixedSequence.push(newWords[newIndex])
          newIndex++
        } else {
          break
        }
      }
      
      sequence.push(...mixedSequence)
  }
  
  return sequence.slice(0, count)
}

// 计算学习目标达成情况
export const calculateGoalAchievement = (goals, progress) => {
  const achievements = []
  
  goals.forEach(goal => {
    const currentValue = progress[goal.metric] || 0
    const targetValue = goal.target
    const progressPercentage = Math.min((currentValue / targetValue) * 100, 100)
    const isAchieved = currentValue >= targetValue
    
    achievements.push({
      ...goal,
      currentValue,
      progressPercentage: Math.round(progressPercentage),
      isAchieved
    })
  })
  
  return achievements
}

// 跟踪学习会话
export const trackLearningSession = (startTime, endTime, wordsLearned, wordsReviewed) => {
  const duration = endTime - startTime
  const efficiency = calculateLearningEfficiency(duration, wordsLearned + wordsReviewed)
  
  return {
    startTime,
    endTime,
    duration,
    wordsLearned,
    wordsReviewed,
    totalWordsProcessed: wordsLearned + wordsReviewed,
    efficiency,
    date: new Date().toISOString()
  }
}

// 计算记忆保留率
export const calculateRetentionRate = (wordStats) => {
  if (!wordStats || !wordStats.length) return 0
  
  const totalWords = wordStats.length
  const retainedWords = wordStats.filter(stat => 
    stat.masteryLevel >= 3 && 
    stat.lastReviewed > Date.now() - 30 * 24 * 60 * 60 * 1000 // 30天内
  ).length
  
  return Math.round((retainedWords / totalWords) * 100)
}

// 生成学习统计数据
export const generateLearningStats = (wordStats, studySessions) => {
  // 总单词数
  const totalWords = wordStats.length
  
  // 已掌握单词数
  const masteredWords = wordStats.filter(stat => stat.masteryLevel >= 4).length
  
  // 需要复习的单词数
  const wordsToReview = getWordsToReview(wordStats).length
  
  // 今日学习单词数
  const today = new Date().toDateString()
  const todayWords = wordStats.filter(stat => 
    new Date(stat.lastReviewed).toDateString() === today
  ).length
  
  // 总学习时间
  const totalStudyTime = studySessions.reduce((sum, session) => sum + session.duration, 0)
  
  // 平均学习时长（分钟）
  const avgStudyTime = studySessions.length > 0 
    ? totalStudyTime / studySessions.length / 60 
    : 0
  
  // 学习效率
  const totalWordsProcessed = studySessions.reduce((sum, session) => 
    sum + session.totalWordsProcessed, 0
  )
  const overallEfficiency = totalWordsProcessed > 0 
    ? calculateLearningEfficiency(totalStudyTime, totalWordsProcessed) 
    : 0
  
  // 记忆保留率
  const retentionRate = calculateRetentionRate(wordStats)
  
  // 按难度分组的单词数
  const difficultyGroups = groupWordsByDifficulty(wordStats)
  
  return {
    totalWords,
    masteredWords,
    wordsToReview,
    todayWords,
    totalStudyTime,
    avgStudyTime: Math.round(avgStudyTime * 10) / 10,
    overallEfficiency,
    retentionRate,
    difficultyDistribution: {
      veryEasy: difficultyGroups[1].length,
      easy: difficultyGroups[2].length,
      medium: difficultyGroups[3].length,
      hard: difficultyGroups[4].length,
      veryHard: difficultyGroups[5].length
    },
    lastStudyDate: studySessions.length > 0 
      ? new Date(Math.max(...studySessions.map(s => s.endTime))).toISOString() 
      : null
  }
}

// 生成学习提醒
export const generateLearningReminder = (studyPlan, lastStudySession) => {
  const reminders = []
  const now = Date.now()
  
  // 检查是否需要每日学习提醒
  if (studyPlan && studyPlan.reminderEnabled) {
    const { reminderTime } = studyPlan
    const [hours, minutes] = reminderTime.split(':').map(Number)
    const reminderDate = new Date()
    reminderDate.setHours(hours, minutes, 0, 0)
    
    // 如果今天的提醒时间已过，设置为明天
    if (reminderDate < now) {
      reminderDate.setDate(reminderDate.getDate() + 1)
    }
    
    reminders.push({
      type: 'daily',
      time: reminderDate.getTime(),
      message: `是时候进行每日学习了！您的目标是每天学习${studyPlan.dailyGoal}个单词。`
    })
  }
  
  // 检查是否长时间未学习
  if (lastStudySession) {
    const daysSinceLastStudy = (now - lastStudySession.endTime) / (1000 * 60 * 60 * 24)
    
    if (daysSinceLastStudy >= 2) {
      reminders.push({
        type: 'catchup',
        time: now + 3600000, // 1小时后
        message: `您已经${Math.floor(daysSinceLastStudy)}天没有学习了，建议尽快复习以保持记忆。`
      })
    }
  }
  
  // 检查是否有大量单词需要复习
  const { wordsToReview } = generateLearningStats([], []) // 这里需要实际的单词统计数据
  if (wordsToReview > 20) {
    reminders.push({
      type: 'review',
      time: now,
      message: `您有${wordsToReview}个单词需要复习，建议优先复习这些单词。`
    })
  }
  
  // 按时间排序提醒
  reminders.sort((a, b) => a.time - b.time)
  
  return reminders
}

// 解析单词数据
export const parseWordData = (wordData) => {
  // 标准化单词数据格式
  const parsedWord = {
    id: wordData.id || generateId('word'),
    text: wordData.text || '',
    pronunciation: wordData.pronunciation || '',
    definitions: Array.isArray(wordData.definitions) ? wordData.definitions : [wordData.definition || ''],
    examples: Array.isArray(wordData.examples) ? wordData.examples : [wordData.example || ''],
    synonyms: Array.isArray(wordData.synonyms) ? wordData.synonyms : [],
    antonyms: Array.isArray(wordData.antonyms) ? wordData.antonyms : [],
    partOfSpeech: wordData.partOfSpeech || '',
    language: wordData.language || 'en',
    createdAt: wordData.createdAt || Date.now(),
    updatedAt: wordData.updatedAt || Date.now()
  }
  
  // 清理空数组
  if (!parsedWord.definitions[0]) parsedWord.definitions = []
  if (!parsedWord.examples[0]) parsedWord.examples = []
  
  return parsedWord
}

// 生成学习笔记
export const generateStudyNote = (word, notes = '') => {
  const timestamp = new Date().toISOString()
  
  return {
    id: generateId('note'),
    wordId: word.id,
    content: notes,
    timestamp,
    word: {
      text: word.text,
      pronunciation: word.pronunciation,
      definition: word.definitions[0] || ''
    }
  }
}

// 辅助函数：生成唯一ID
const generateId = (prefix = 'id') => {
  return `${prefix}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
}